# @FileName  : xlsx.py
# @Time      : 2025/3/6 08:56
# @Author    : LuZhaoHui
# @Software  : PyCharm
import inspect
import os
import xlsxwriter, openpyxl
import csv, codecs


def cur_func(err):
    return '%s:%s' % (inspect.currentframe(), str(err))


def write_xlsx(name, data):
    try:
        write = xlsxwriter.Workbook(name)
        sheet = write.add_worksheet()
        for i, cols in enumerate(data):
            for j, d in enumerate(cols):
                if isinstance(d, list):
                    l = len(d)
                    for k, dd in enumerate(d):
                        sheet.write(i, j * l + k, dd)
                else:
                    sheet.write(i, j, d)
        write.close()
    except Exception as e:
        print(cur_func(e))


def write_csv(name, data):
    try:
        file_csv = codecs.open(name, 'w+', 'utf-8')
        writer = csv.writer(file_csv, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for d in data:
            writer.writerow(d)
    except Exception as e:
        print(cur_func(e))


def add_csv(name, data):
    try:
        file_csv = codecs.open(name, 'a', 'utf-8')
        writer = csv.writer(file_csv, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for d in data:
            writer.writerow(d)
    except Exception as e:
        print(cur_func(e))


def read_xlsx(name):
    data = []
    if os.path.exists(name):
        read = openpyxl.load_workbook(name)
        sheets = read.get_sheet_names()
        sheet = read.get_sheet_by_name(sheets[0])
        rows = sheet.rows
        for row in rows:
            line = [col.value for col in row]
            data.append(line)
    return data


def read_csv(name, csv_type):
    data = []
    if os.path.exists(name):
        if os.path.exists(name):
            with open(name, encoding='utf-8') as csvfile:
                csv_reader = csv.reader(csvfile)
                csv_cmd = 'data.append(row)'
                if len(csv_type) > 0:
                    csv_cmd = 'data.append(['
                    for i, t in enumerate(csv_type):
                        if t == 'int':
                            csv_cmd += 'int(row[%d]),' % i
                            continue
                        if t == 'float':
                            csv_cmd += 'float(row[%d]),' % i
                            continue
                        csv_cmd += 'row[%d],' % i
                    csv_cmd = csv_cmd[:-1] + '])'
                for row in csv_reader:
                    exec(csv_cmd)
                # data.append(row)
    return data
